from django.shortcuts import render
from django.http import JsonResponse
from . import models
import threading
from function import views as functionviews

# record user's status: true-> login; false -> logout
user_login = {}


def login_page(request):
    return render(request, 'login.html')


def register_page(request):
    return render(request, 'register.html')


def check_login(request):
    # parse parameters
    username = request.POST['username']
    password = request.POST['password']
    # select database
    user = models.Login.objects.filter(username=username, password=password)
    if user.exists():
        # create thread
        if username not in user_login.keys():
            user_login[username] = True
        threading.Thread(target=functionviews.thread_free_code_editor, args=(username,)).start()
        # return home page
        return render(request, 'home.html', {'username': username})
    else:
        return render(request, 'login.html')


def register_user(request):
    # parse parameters
    username = request.POST['username']
    email = request.POST['email']
    password = request.POST['password']
    # insert user info into database
    models.Login.objects.create(username=username, email=email, password=password)
    # return page
    return render(request, 'login.html')


def check_username_is_exist(request):
    # parameter
    check_username = request.GET['username']
    # select database
    users = models.Login.objects.all()
    usernames = [user.username for user in users]
    # judge
    if check_username in usernames:
        return JsonResponse({"result": True})
    else:
        return JsonResponse({"result": False})


def registerUser(request):
    models.Login.objects.create(username='lgw', email='1369375419@qq.com', password='123456')
    return render(request, 'login.html')


def user_logout(request):
    result = 'ok'
    username = request.POST['username']
    try:
        user_login[username] = False
    except:
        result = 'failed'
    finally:
        return JsonResponse({'result': result})


def test(request):
    return render(request,'live-table.html')